/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, {Component} from 'react';
import {
    Image,
    ScrollView,
    ListView,
    Animated,
    TouchableOpacity,
    TouchableHighlight,
    Alert,
    StyleSheet,
    DeviceEventEmitter,
    RefreshControl,
    InteractionManager,
    Text,
    View,
    Modal,
    Platform,
}
    from 'react-native';
import StyleUtils from "../../../res/styles/StyleUtils";
import Navigation from "../../../custom/Navigation";
import ViewUtils from "../../../utils/ViewUtils";
import ModalListUtils from "../../../utils/ModalListUtils";
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view'
import IparNetwork, {SERVER_TYPE} from "../../../httpUtils/IparNetwork";
import I18n from '../../../res/language/i18n'
import CommonUtils from "../../../common/CommonUtils";
import AlertDialog from "../../../custom/AlertDialog";
import IparInput from "../../../custom/IparInput";
import RegisterIBMOnePage from "./RegisterIBMOnePage";
import RegisterRecommenderAlert from "../../../utils/RegisterRecommenderAlert";

let clickTypes = {
    country: 'country',
    sex: 'sex',
    country_code: 'country code',
    verification_Code: 'verification_Code',
    register: 'REGISTER'
};

export default class RegisterCustomerPage extends Component {


    constructor(props) {
        super(props);
        this.iparNetwork = new IparNetwork();


        let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});

        this.state = {

            modalVisible: false,
            modalType: null,//国家还是性别。。。
            countryDataSource: ds.cloneWithRows(this.props.countryData),
            countryCodeData: ds,
            verificationTimer: I18n.t('default.sendVerCode'),
            /**
             * 默认text
             */
            countryText: '',
            alertVisible: false,
            userName: '',
            user_id: '',
            country: null,
            countryCodeText: I18n.t('default.countryCode'),
            recommenderAlertVisible: false,
        }
    }


    /**
     * finish page的时候
     */
    componentWillUnmount() {
        this._timer && clearInterval(this._timer);
    }

    /**
     * render方法完成后
     */
    componentDidMount() {
        // this.onLoadCountry()
    }


    // /**
    //  * 获取国家信息
    //  */
    // onLoadCountry() {
    // 	this.iparNetwork.getRequest(SERVER_TYPE.logistics + 'region?', 'lang=EN')
    // 		.then((result) => {
    // 			if (result) {
    // 				this.countryData = result;
    // 				this.setState({
    // 					countryDataSource: this.state.countryDataSource.cloneWithRows(result),
    // 				})
    // 			}
    // 		})
    // 		.catch((error) => {
    // 			DeviceEventEmitter.emit('toast', error);
    // 		})
    // }


    /**
     * 更新  loading
     * @param isLoading
     */
    showLoading(isLoading) {
        if (isLoading) {
            CommonUtils.showLoading();
        } else {
            CommonUtils.dismissLoading();
        }
    }


    /**
     * modal item click
     * @param index
     * @param text
     */
    onItemClick(index, text) {
        if (this.state.modalType === clickTypes.country_code) {
            this.selectCountryCode = this.props.countryData[index].area_code;
            this.setState({
                modalVisible: false,
                countryCodeText: text,
            })
        } else if (this.state.modalType === clickTypes.country) {
            this.selectCountryIso = this.props.countryData[index].iso;
            this.setState({
                modalVisible: false,
                countryText: text,
            })
        } else {
            this.setState({
                modalVisible: false,
                countryText: text,
            })
        }
    }


    /**
     * 点击事件
     * */
    _onClick(type) {

        switch (type) {
            case clickTypes.country:
                this.setState({
                    modalVisible: true,
                    modalType: clickTypes.country,
                });
                break;
            case clickTypes.sex:
                this.setState({
                    modalVisible: true,
                    modalType: clickTypes.sex,
                });
                break;
            case clickTypes.country_code:
                this.setState({
                    modalVisible: true,
                    modalType: clickTypes.country_code,
                });
                break;
            case clickTypes.verification_Code:
                if (!this.checkInput()) {//是否输入用户名手机号。。。。
                    return
                }
                this.checkUserKey();
                break;
            case  clickTypes.register:
                this.register();
                break;
            case  clickTypes.lang:

                break;
        }
    }


    /**
     * 验证-手机号
     */
    checkUserKey() {
        this.showLoading(true);
        this.iparNetwork.getRequest(SERVER_TYPE.admin + 'checkUserKey?', 'keywords=' + this.userPhoneNumber)
            .then((result) => {
                if (result.code === 200) {//用户已存在
                    this.showLoading(false);
                    DeviceEventEmitter.emit('toast', I18n.t('default.userHasAlready'))
                } else {//用户未存在
                    this.sendVerificationCode()
                }
            })
            .catch((error) => {
                this.showLoading(false);
                console.log(error);
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
            });
    }


    /**
     * 发送验证码
     */
    sendVerificationCode() {
        this.stopTime();

        this.iparNetwork.getRequest(SERVER_TYPE.adminIpar + 'sms?',
            'phone=' + this.userPhoneNumber + '&type=register&country=' + this.selectCountryCode)
            .then((result) => {
                this.showLoading(false);
                if (result.code === 200) {
                    this.countTime();
                    console.log(result);
                    DeviceEventEmitter.emit('toast', I18n.t('toast.sendVerCodeSuccess'));
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'));
                }
            })
            .catch((error) => {
                this.showLoading(false);
                console.log(error);
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
            });

    }


    /**
     * 发送验证码的效果（btn 的 文字（59...））
     */
    countTime() {
        this._index = 60;
        this._timer = setInterval(() => {
            this.setState({verificationTimer: this._index-- + ' s'});
            if (this.state.verificationTimer <= 0 + ' s') {
                this._timer && clearInterval(this._timer);
                this.setState({verificationTimer: I18n.t('toast.againGetCode')});
            }
        }, 1000);
    }

    stopTime() {
        this._timer && clearInterval(this._timer);
        this.setState({verificationTimer: I18n.t('toast.againGetCode') + '...'});
    }


    checkInput() {
        if (this.state.countryText === '') {
            DeviceEventEmitter.emit('toast', I18n.t('default.selectCountry'));
            return false;
        }
        if (!this.userName || !this.userName.trim()) {
            DeviceEventEmitter.emit('toast', I18n.t('default.enterUserName'));
            return false;
        }

        if (this.state.countryCodeText === I18n.t('default.countryCode')) {
            DeviceEventEmitter.emit('toast', I18n.t('default.countryCode'));
            return false;
        }
        if (!this.userPhoneNumber || !this.userPhoneNumber.trim()) {
            DeviceEventEmitter.emit('toast', I18n.t('default.enterPhoneNum'));
            return false;
        }
        return true;
    }


    /**
     * 用户注册
     */
    register() {


        if (!this.checkInput()) {
            return
        }

        if (!this.verificationCode || !this.verificationCode.trim()) {
            DeviceEventEmitter.emit('toast', I18n.t('toast.enterVerification'));
            return
        }
        if (!this.userPass) {
            DeviceEventEmitter.emit('toast', I18n.t('default.enterPass'));
            return
        }
        if (!CommonUtils.isPassword(this.userPass)) {
            DeviceEventEmitter.emit('toast', I18n.t('toast.isNotPassword'));
            return;
        }


        this.showLoading(true);


        // let _lang = 'en';
        // switch (this.selectCountryIso) {
        // 	case 'CN':
        // 		_lang = 'zh';
        // 		break;
        // 	case 'KZ':
        // 	case 'KG':
        // 	case 'RU':
        // 	case 'AZ':
        // 		_lang = 'ru';
        // 		break;
        // }


        let formData = new FormData();
        formData.append('country', this.selectCountryIso);//iso
        formData.append('nick_name', this.userName);
        formData.append('area_code', this.selectCountryCode);
        formData.append('mobile', this.userPhoneNumber);
        formData.append('code', this.verificationCode);
        formData.append('user_pass', this.userPass);
        formData.append('is_contract', 1);
        // formData.append('user_name', this.userPhoneNumber);
        formData.append('froms', Platform.OS === 'ios' ? 'IOS' : 'Android');
        formData.append('lang', I18n.locale.toUpperCase());
        this.iparNetwork.getPostFrom(SERVER_TYPE.admin + 'addUserInfo', formData, '')
            .then((result) => {
                this.showLoading(false);
                if (result.code === 200) {
                    this.registerSuccess(result.data);
                    this.sendRegisterSms(this.userPass, this.userPhoneNumber, this.selectCountryIso);
                } else if (result.code === 444) {
                    DeviceEventEmitter.emit('toast', I18n.t('default.verCodeError'))
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('toast.registerFail'))
                }
            })
            .catch((error) => {
                console.log('RegisterCustomerPage---register--error:' + error);
                DeviceEventEmitter.emit('toast', I18n.t('toast.registerFail'))
            })
    }


    /**
     * 注册成功
     * @param userInfo
     */
    registerSuccess(userInfo) {
        DeviceEventEmitter.emit('toast', I18n.t('toast.registerSuccessful'));

        if (this.props.registerType === 'ibm') {//IBM注册
            this.setState({
                alertVisible: true,
                user_id: userInfo.main_user_id,
                country: userInfo.country,
            });
        } else {// VIP注册
            this.userInfo = userInfo;
            this.setState({
                recommenderAlertVisible: true,
            });
        }
    }


    sendRegisterSms(password, phone, country) {
        let formData = new FormData();
        formData.append("password", password);
        formData.append("phone", phone);
        formData.append("country", country);
        this.iparNetwork.getPostFrom(SERVER_TYPE.adminIpar + "sendRegisterSms", formData)
            .then((result) => {
                console.log(result)
            });
    }


    startIBM_Page(user_id) {
        this.props.navigator.push({
            component: RegisterIBMOnePage,
            name: 'RegisterIBMOnePage',
            params: {
                userId: user_id,
                country: this.state.country,
            }
        })
    }

    /**
     * init
     * */
    render() {
        //modal 的数据
        let modalDataPram = 'name';
        if (this.state.modalType === clickTypes.country_code) {
            modalDataPram = 'area_code'
        }


        return (
            <View style={[StyleUtils.flex, {backgroundColor: 'white'}]}>
                <Navigation
                    onClickLeftBtn={() => this.props.navigator.pop()}
                    titleImage={require('../../../res/images/ic_ipar_logo.png')}
                />
                <KeyboardAwareScrollView
                >
                    <View style={[{padding: 16}]}>

                        {/*title*/}
                        {ViewUtils.getTitleView(I18n.t('default.register'),
                            I18n.t('default.registerBasic'),)}


                        {ViewUtils.getButtunMenu(this.state.countryText ? this.state.countryText : I18n.t('default.selectCountry'), () => this._onClick(clickTypes.country))}

                        {/**选择国家*/}
                        <ModalListUtils
                            close={() => {
                                this.setState({
                                    modalVisible: false
                                })
                            }}
                            onPress={(index, text) => this.onItemClick(index, text)}
                            dataParam={modalDataPram}
                            title={modalDataPram === 'area_code' ? I18n.t('default.selectCountryCalling') : I18n.t('default.selectCountry')}
                            visible={this.state.modalVisible}
                            dataSource={this.state.countryDataSource}
                        />

                        <IparInput
                            onChangeText={(test) => this.userName = test}
                            placeholder={I18n.t('default.enterUserName')}/>

                        <View style={[StyleUtils.center, StyleUtils.justifySpace, StyleUtils.marginTop]}>
                            {ViewUtils.getButtunMenu(this.state.countryCodeText, () => this._onClick(clickTypes.country_code), {width: '40%'})}

                            <IparInput
                                keyboardType={'number-pad'}
                                style={{
                                    marginTop: 0,
                                    width: '54%'
                                }}
                                onChangeText={(test) => this.userPhoneNumber = test}
                                placeholder={I18n.t('default.phoneNumber')}/>

                        </View>


                        <View style={[StyleUtils.center, StyleUtils.justifySpace, StyleUtils.marginTop]}>

                            <IparInput
                                keyboardType={'number-pad'}
                                style={{
                                    marginTop: 0,
                                    width: '64%'
                                }}
                                onChangeText={(test) => this.verificationCode = test}
                                placeholder={I18n.t('toast.enterVerification')}/>

                            {ViewUtils.getButton(this.state.verificationTimer, () => this._onClick(clickTypes.verification_Code), {width: '33%'}, {fontSize: 14})}

                        </View>

                        <IparInput
                            isPassword={true}
                            onChangeText={(test) => this.userPass = test}
                            placeholder={I18n.t('default.enterPass')}/>

                        {ViewUtils.getButton(I18n.t('default.submit'), () => this._onClick(clickTypes.register), [StyleUtils.marginBottom, StyleUtils.marginTop])}
                    </View>
                </KeyboardAwareScrollView>


                <AlertDialog
                    contentTv={I18n.t('toast.registerSuccessfulIBM')}
                    rightSts={I18n.t('default.notNow')}
                    leftBtnOnclick={() => {
                        this.setState({alertVisible: false}, this.startIBM_Page(this.state.user_id));
                    }}
                    rightBtnOnclick={() => new CommonUtils().popToRoute(this, 'LoginPage')}
                    visible={this.state.alertVisible}
                    requestClose={() => this.setState({alertVisible: false})}/>


                <RegisterRecommenderAlert
                    requestClose={() => {
                        this.setState({
                            recommenderAlertVisible: false,
                        })
                    }}
                    userInfo={this.userInfo}
                    success={() => {
                        new CommonUtils().popToRoute(this, 'LoginPage');
                    }}
                    visible={this.state.recommenderAlertVisible}/>


            </View>
        );
    }
}




